<template>
  <div class="full-reduction-detail-page">
    <el-main class="main-content">
      <h2 class="page-title">{{ activity.name }} - 满减活动详情</h2>
      
      <!-- Activity Info -->
      <el-card class="activity-info-card" shadow="hover">
        <div class="activity-info">
          <h3 class="activity-title">{{ activity.name }}</h3>
          <p class="info-item">活动时间: {{ formatDate(activity.startTime) }} - {{ formatDate(activity.endTime) }}</p>
          <p class="info-item">状态: {{ getActivityStatus(activity.status) }}</p>
          <p class="info-item">满减标准: {{ activity.threshold }}</p>
          <p class="info-item">活动配置: {{ activity.discount }}</p>
        </div>
      </el-card>

      <!-- Full Reduction Items -->
      <h3 class="section-title">满减商品 (满¥{{ fullReductionItems[0]?.threshold }}减¥{{ fullReductionItems[0]?.discount }})</h3>
      <el-row :gutter="20" class="full-reduction-items-grid">
        <el-col :span="6" v-for="item in fullReductionItems" :key="item.skuId" class="full-reduction-item-card">
          <el-card :body-style="{ padding: '0px' }" shadow="hover">
            <div class="item-content">
              <img :src="item.skuImage || item.spuMainImage" class="item-image" alt="商品图片" />
              <div class="item-info">
                <h4 class="item-title">{{ item.skuName }}</h4>
                <p class="item-price">单价: ¥{{ item.skuPrice }}</p>
                <div class="action-row">
                  <div class="quantity-selector">
                    <span class="quantity-label">选择数量:</span>
                    <el-input-number
                      v-model="item.quantity"
                      :min="0"
                      size="small"
                      :disabled="isSubmitting[item.skuId]"
                      @change="handleQuantityChange(item)"
                      class="quantity-input"
                    />
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <div class="order-summary">
        <p>已选商品总金额: ¥{{ totalAmount }}</p>
        <p>优惠金额: ¥{{ promotionAmount }}</p>
        <p>应付金额: ¥{{ payAmount }}</p>
        <p class="threshold-tip" :class="{ 'reached': isThresholdReached }">
          {{ thresholdTip }}
        </p>
        <el-button
          type="danger"
          :disabled="selectedItems.length === 0 || isSubmittingOrder"
          :loading="isSubmittingOrder"
          @click="placeOrder"
        >立即购买</el-button>
      </div>
      <!-- Pagination -->
      <div class="pagination" v-if="itemTotal > 0">
        <el-pagination
          v-model:current-page="itemCurrentPage"
          v-model:page-size="itemPageSize"
          :total="itemTotal"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleItemPageSizeChange"
          @current-change="handleItemPageChange"
        />
      </div>
    </el-main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getFullReductionActivity, getFullReductionItems, placeFullReductionOrder } from '@/api/promotion';
import { useUserInfoStore } from '@/stores/userInfo';

const userInfoStore = useUserInfoStore();
const route = useRoute();
const router = useRouter();
const activityId = ref(route.params.promotionId);
const activity = ref({});
const fullReductionItems = ref([]);
const itemCurrentPage = ref(1);
const itemPageSize = ref(10);
const itemTotal = ref(0);
const isSubmitting = ref({});
const isSubmittingOrder = ref(false);

const selectedItems = computed(() => fullReductionItems.value.filter(item => item.quantity > 0));

const totalAmount = computed(() => {
  return selectedItems.value.reduce((sum, item) => sum + item.skuPrice * item.quantity, 0).toFixed(2);
});

const promotionAmount = computed(() => {
  const threshold = fullReductionItems.value[0]?.threshold || 0;
  const discount = fullReductionItems.value[0]?.discount || 0;
  return totalAmount.value >= threshold ? discount.toFixed(2) : '0.00';
});

const payAmount = computed(() => {
  return (totalAmount.value - promotionAmount.value).toFixed(2);
});

const isThresholdReached = computed(() => {
  const threshold = fullReductionItems.value[0]?.threshold || 0;
  return Number(totalAmount.value) >= Number(threshold);
});

const fetchActivity = async () => {
  try {
    const response = await getFullReductionActivity(activityId.value);
    if (response.data.code === "0" || response.data.code === "200") {
      activity.value = response.data.data;
    } else {
      ElMessage.error(response.data.message || '获取满减活动失败');
    }
  } catch (error) {
    ElMessage.error('获取满减活动失败');
  }
};

const fetchFullReductionItems = async (page = 1, size = 10) => {
  try {
    const response = await getFullReductionItems(activityId.value, page, size);
    console.log(response)
    if (response.data.code === "0" || response.data.code === "200") {
      fullReductionItems.value = response.data.data.records.map(item => ({
        ...item,
        quantity: 0,
        skuPrice: item.skuPrice || 0 // 假设后端返回sku价格
      }));
      itemTotal.value = response.data.data.records.length;
      itemCurrentPage.value = page;
      itemPageSize.value = size;
      fullReductionItems.value.forEach(item => {
        isSubmitting.value[item.skuId] = false;
      });
    } else {
      ElMessage.error(response.data.message || '获取满减商品失败');
    }
  } catch (error) {
    ElMessage.error('获取满减商品失败');
  }
};

const placeOrder = async () => {
  if (selectedItems.value.length === 0) {
    ElMessage.error('请至少选择一种商品');
    return;
  }
  try {
    isSubmittingOrder.value = true;
    const userId = userInfoStore.userInfo.id;
    const skuQuantities = {};
    selectedItems.value.forEach(item => {
      skuQuantities[item.skuId] = item.quantity;
    });
    const response = await placeFullReductionOrder({
      userId,
      activityId: activityId.value,
      skuQuantities
    });
    if (response.data.code === "0" || response.data.code === "200") {
      const orderSn = response.data.data.orderSn;
      router.push({ path: '/pay/choose', query: { orderSn } });
    } else {
      ElMessage.error(response.data.message || '下单失败');
    }
  } catch (error) {
    ElMessage.error('下单失败');
  } finally {
    isSubmittingOrder.value = false;
  }
};

const handleQuantityChange = (item) => {
  if (item.quantity < 0) {
    item.quantity = 0;
    ElMessage.warning('购买数量不能小于0');
  }
};

const handleItemPageChange = async () => {
  await fetchFullReductionItems(itemCurrentPage.value, itemPageSize.value);
};

const handleItemPageSizeChange = async () => {
  itemCurrentPage.value = 1;
  await fetchFullReductionItems(1, itemPageSize.value);
};

const getActivityStatus = (status) => {
  const statuses = { 0: '停用', 1: '启用' };
  return statuses[status] || '未知';
};

const formatDate = (dateStr) => {
  return dateStr ? new Date(dateStr).toLocaleString() : 'N/A';
};

onMounted(async () => {
  await Promise.all([
    fetchActivity(),
    fetchFullReductionItems()
  ]);
  // 显示优惠券弹窗
  if (activity.value.threshold && activity.value.discount) {
    ElMessageBox.alert(
      `恭喜您获得满${activity.value.threshold}减${activity.value.discount}的优惠券！`,
      '优惠券领取成功',
      {
        confirmButtonText: '确定',
        type: 'success'
      }
    );
  }
});
</script>

<style scoped>
.full-reduction-detail-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 16px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 24px;
  text-align: center;
}

.main-content {
  margin: 24px 0;
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 48px);
}

.activity-info-card {
  margin-bottom: 24px;
  border-radius: 12px;
}

.activity-info {
  padding: 16px;
}

.activity-title {
  font-size: 20px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 16px;
}

.info-item {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.section-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin: 24px 0 16px;
}

.full-reduction-items-grid {
  margin-bottom: 24px;
}

.full-reduction-item-card .el-card {
  border-radius: 12px;
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
}

.full-reduction-item-card .el-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.15);
}

.item-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
}

.item-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  margin-bottom: 12px;
}

.item-info {
  text-align: center;
  width: 100%;
}

.item-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
}

.item-price {
  font-size: 14px;
  color: #f56c6c;
  font-weight: 500;
  margin-bottom: 4px;
}

.action-row {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-top: 8px;
}

.quantity-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-label {
  font-size: 14px;
  color: #606266;
}

.quantity-input {
  width: 100px;
}

.order-summary {
  margin: 20px 0;
  text-align: right;
}

.order-summary p {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.order-summary .el-button {
  margin-top: 8px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: flex-end;
}
</style>